package com.yh.workbill.ui.home.mvp;

import android.util.Log;

import com.yh.workbill.model.WorkBill;
import com.yh.workbill.ui.home.HomeViewModel;
import com.yh.workbill.ui.mvp.MainModel;

import java.util.ArrayList;
import java.util.List;

import androidx.arch.core.executor.ArchTaskExecutor;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.OnLifecycleEvent;

public class Home_Presenter implements LifecycleObserver {
    private Home_View home_view;
    private Home_Model home_model;

    public Home_Presenter(Home_View view) {
        this.home_view = view;
        this.home_model = new Home_Model();
    }

    public void getWorkBill(HomeViewModel viewModel, boolean isRefresh, boolean isLoadMore, String user_uuid, int pageindex, int pagenumber) {
        ArchTaskExecutor.getMainThreadExecutor().execute(() -> home_view.showDialog("正在加载数据...", true));
        home_model.getWorkBillData(user_uuid, pageindex, pagenumber, new Home_Model.HomeCallback() {
            @Override
            public void successWorkBillData(List<WorkBill> data) {
                ArchTaskExecutor.getMainThreadExecutor().execute(() -> {
//                    Log.e("TAG", "请求到的数据是:\n" + data);
                    WorkBill[] workBills = data.toArray(new WorkBill[data.size()]);
                    if (isRefresh) {
                        if (viewModel.getWorkBilldata().getValue() != null) {
                            viewModel.getWorkBilldata().getValue().clear();
                        }
                        viewModel.addworkBilldatas(0, workBills);
                        home_view.refresh();
                    } else if (isLoadMore) {
                        int index = viewModel.getWorkBilldata().getValue().size();
                        viewModel.addworkBilldatas(index, workBills);
                        home_view.loadMore();
                    }
                    home_view.GetDataSuccess();
                    home_view.hideDialog();
                });
            }

            @Override
            public void fail(String msg) {
                ArchTaskExecutor.getMainThreadExecutor().execute(() -> {
                    home_view.showTasot(msg);
                    home_view.hideDialog();
                    home_view.GetDataFail();
                });
            }
        });
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void ondestorey() {
        if (this.home_view != null) {
            this.home_view = null;
        }
    }
}
